package org.example.buysystem.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.buysystem.common.Result;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.Address;
import org.example.buysystem.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/address")
@CrossOrigin
@Api(value = "地址",tags = {"地址接口"})
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("/{userId}")
    @ApiOperation("根据用户id获取地址")
    public Result getAddressByUserId(@PathVariable Long userId){
        if (userId == null) {
            return Result.error(Constants.CODE_500,"用户id不能为空");
        }
        return Result.success(addressService.findAllById(userId));
    }

    @GetMapping
    @ApiOperation("查询所有地址信息")
    public Result findAll(){
        List<Address> list=addressService.list();
        return Result.success(list);
    }

    @PostMapping
    @ApiOperation("保存地址")
    public Result save(@RequestBody Address address){
        boolean flag=addressService.saveOrUpdate(address);
        if (flag){
            return Result.success();
        }else {
            return Result.error(Constants.CODE_500,"保存地址失败");
        }
    }

    @PutMapping
    @ApiOperation("修改地址")
    public Result update(@RequestBody Address address){
        addressService.updateById(address);
        return Result.success();

    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除地址")
    public Result delete(@PathVariable int id){
        addressService.removeById(id);
        return Result.success();
    }



}
